<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <template>
        <el-table
          :data="tableData"
          stripe
          border
          style="width: 100%">
          <el-table-column
            type="expand">
            <template slot-scope="scope">
              <el-row :class="['bdbottom',i1 ===0 ? 'bdtop' : '' ]" v-for="(item1 ,i1) in scope.row.children"
                      :key="item1.id">
                <el-col :span="5">
                  <el-tag closable @close="removeRightByid(scope.row , item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <!-- 通过for循环嵌套二级权限    -->
                  <el-row :class="['bdbottom',i2 ===0 ? 'bdtop' : '' ]" v-for="(item2,i2) in item1.children"
                          :key="item2.id">
                    <el-col :span="6">
                      <el-tag closable @close="removeRightByid(scope.row , item2.id)" type="success">
                        {{item2.authName}}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag closable @close="removeRightByid(scope.row , item3.id)" v-for="(item3) in item2.children"
                              :key="item3.id"
                              type="warning">
                        {{item3.authName}}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column
            prop="authName"
            label="#"
            type="index">
          </el-table-column>
          <el-table-column
            prop="roleName"
            label="角色名称">
          </el-table-column>
          <el-table-column
            prop="roleDesc"
            label="角色描述">
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-tooltip content="编辑" placement="top">
                <el-button type="primary" icon="el-icon-edit" size="mini"
                           @click="showeditdialog(scope.row.id)">编辑
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button type="danger" icon="el-icon-delete" size="mini"
                           @click="removeRolesByid(scope.row.id)">删除
                </el-button>
              </el-tooltip>
              <el-tooltip content="分配权限" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini"
                           @click="showRightDialog(scope.row)">分配权限
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 分配权限dialog框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogFormVisible"
               @close="setRightDialogClosed">
      <!--树形控件-->
      <el-tree :data="rightTreedata" :props="defaultProps" show-checkbox
               node-key="id" default-expand-all :default-checked-keys="defaultTreeKeys"
               ref="treeRef"></el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRightDialogFormVisible">确 定</el-button>
      </div>
    </el-dialog>

    <!--修改角色的对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="editdialogVisible"
      width="50%"
      @close="editDialogClosed('editFormRef')">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRole('editFormRef')">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: 'Roles',
  data () {
    return {
      tableData: [],
      setRightDialogFormVisible: false,
      rightTreedata: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      defaultTreeKeys: [],
      roleId: '',
      editForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      editdialogVisible: false,
      editFormRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: '请输入角色描述',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async gettableData () {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.tableData = res.data
      console.log(res)
    },
    editRole (editFormRef) {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          })
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          } else {
            this.$message.success(res.meta.msg)
            this.editdialogVisible = false
            this.gettableData()
          }
        } else {
          return false
        }
      })
    },
    editDialogClosed (refForm) {
      this.$refs[refForm].resetFields()
    },
    async showeditdialog (id) {
      this.editdialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.editForm = res.data
      }
    },
    removeRightByid (row, id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${id}`)
        console.log(res)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '取消权限成功!'
          })
          row.children = res.data
        } else {
          this.$message({
            type: 'error',
            message: '取消权限失败!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    removeRolesByid (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        console.log(res)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除角色成功!'
          })
          this.gettableData()
        } else {
          this.$message({
            type: 'error',
            message: '删除角色失败!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async showRightDialog (row) {
      this.roleId = row.id
      this.setRightDialogFormVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
        this.rightTreedata = res.data
        this.getTreekeyids(row, this.defaultTreeKeys)
      }
    },
    getTreekeyids (node, arr) {
      //如果当前node没有children则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getTreekeyids(item, arr)
      })
    },
    setRightDialogClosed () {
      this.defaultTreeKeys = []
    },
    async saveRightDialogFormVisible () {
      const keys = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
      }
      this.gettableData()
      this.setRightDialogFormVisible = false
    }

  },
  created () {
    this.gettableData()
  }
}
</script>

<style scoped>
  .el-breadcrumb {
    margin-bottom: 15px;
    font-size: 12px;
  }

  .el-card {
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15);
  }

  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }

  .text {
    font-size: 14px;
  }

  .item {
    padding: 18px 0;
  }

  .el-tag {
    margin: 7px;
  }

  .bdbottom {
    border-bottom: 1px solid #eee;
  }

  .bdtop {
    border-top: 1px solid #eee;

  }
  .el-input{
    margin-left: 25px;
    width: 500px;
  }

</style>
